package com.sbp.message.comm;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dap.utils.DateUtil;
import com.google.common.collect.Lists;
import com.sbp.message.api.entity.Message;
import com.sbp.message.api.entity.MessageStatus;
import com.sbp.message.api.entity.MessageType;
import org.apache.commons.codec.Charsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;

public class EmailUtils {
    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    private final static String mailHost = "192.168.11.90";
    private final static String mailHostUser = "sunrise\\wmin02";
    private final static String mailHostPassword = "1234@abcd";
    private final static String mailFrom = "wmin02@shangyuan.cn";

    private static final Properties mailSessionProperties;
    static {
        mailSessionProperties = new Properties();
        mailSessionProperties.setProperty("mail.host", mailHost);
        mailSessionProperties.setProperty("mail.transport.protocol", "smtp");
        mailSessionProperties.setProperty("mail.smtp.auth", "true");
    }


    /**
     * @Method: createSimpleMail
     * @Description: 创建一封只包含文本的邮件
     */
    public static MimeMessage createSimpleMail(Session session, String mailSubject, String mailContent, Address[] recipients) throws Exception {
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //指明邮件的发件人
        mimeMessage.setFrom(new InternetAddress(mailFrom));

        //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
        mimeMessage.setRecipients(MimeMessage.RecipientType.TO, recipients);

        //邮件的标题
        mimeMessage.setSubject(mailSubject);
        //邮件的文本内容
        mimeMessage.setContent(mailContent, "text/html;charset=UTF-8");
        //返回创建好的邮件对象
        return mimeMessage;
    }


    private static Address[] generateRecipients(List<String> notifyEmailList) {
        Address[] recipients = new Address[notifyEmailList.size()];
        for (int i=0; i<notifyEmailList.size(); ++i) {
            try {
                recipients[i] = new InternetAddress(notifyEmailList.get(i));
            } catch (AddressException e) {
            }
        }
        return recipients;
    }

    public static String generateMailSubject(String errorType, Message message, String companyName) {
        return companyName + ", 消息id["+message.getId()+"] " + errorType;
    }
    public static String generateMailContent(String errorType, Message message, String companyName) {
        String messageContentJson = JSON.toJSONString(JSON.parse(message.content), SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.DisableCircularReferenceDetect);
        messageContentJson = convertMultipleLineText(messageContentJson);

        String errorLogHtml;
        if (null == message.getErrorLog() || 0 == message.getErrorLog().length) {
            errorLogHtml = "";
        } else {
            String errorLog = new String(message.getErrorLog(), Charsets.UTF_8);
            errorLog = convertMultipleLineText(errorLog);
            errorLogHtml = "<h1>异常日志:</h1><div style=\"border:1px solid\">" + errorLog + "</div><br/>";
        }

        String kibanaHost;
        if ("shangyuan".equals(companyName)) {
            kibanaHost = "http://kibana.shangyuan.cn";
        } else {
            kibanaHost = "http://kibana.jiujiajiu.com";
        }

        return "<h1>错误类型: " + errorType + "</h1><br/>"
                + "<h1>消息内容:</h1><div style=\"border:1px solid\">" + messageContentJson + "</div><br/>"
                + errorLogHtml

                + "<h1>消息属性:</h1>"
                + "<div>id:" + message.getId() + "</div>"
                + "<div>destination:" + message.getDestination() + "</div>"
                + "<div>发送源头:" + message.getSource() + "</div>"
                + "<div>重试次数:" + message.getRetry() + "</div>"
                + "<div>类型:" + MessageType.valueOf(message.getMessageType()).getDesc() + "</div>"
                + "<div>状态:" + MessageStatus.valueOf(message.getStatus(), true).getDesc() + "</div>"
                + "<div>是否持久化:" + message.getIsPersistence() + "</div>"
                + "<div>当前成功确认数量:" + message.getAcknowledges() + "</div>"
                + "<div>只能人工处理的业务异常的数量:" + message.getBusinessFailed() + "</div>"
                + "<div>确认者信息组成:" + message.getAcknowledgesDescribe() + "</div>"
                + "<div>该条消息的消费者数量(适应于一对多的订阅):" + message.getConsumers() + "</div>"
                + "<div>消费者信息描述:" + message.getConsumersDescribe() + "</div>"
                + "<div>意外消费的消费者名称:" + message.getUnexpectedConsumersDescribe() + "</div>"
                + "<div>创建时间:" + DateUtil.format(message.getCreateTime(),"yyyy-MM-dd HH:mm:ss") + "</div>"
                + "<div>更新时间:" + DateUtil.format(message.getUpdateTime(),"yyyy-MM-dd HH:mm:ss") + "</div>"
                + "<div>traceId:" + message.traceId + "</div>"
                + "<a href=\""+kibanaHost+"/app/kibana#/discover?_g=()&_a=(columns:!(_source),interval:auto,query:(language:lucene,query:'"+message.traceId+"'))\">消息相关日志</a>"
                ;
    }

    private static String convertMultipleLineText(String content) {
        StringBuilder sb = new StringBuilder();
        for (int i=0; i<content.length(); ++i) {
            char ch = content.charAt(i);
            if ('\n' == ch) {
                sb.append("<br/>");
            } else if ('\t' == ch) {
                sb.append("&nbsp;&nbsp;&nbsp;&nbsp;");
            } else if (' ' == ch) {
                sb.append("&nbsp;");
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    public static void sendNotifyEmail(String errorType, Message message, String companyName, List<String> notifyEmailList) throws Exception {
        //1、创建session
        Session session = Session.getInstance(mailSessionProperties);
        session.setDebug(false);

        //2、通过session得到transport对象
        Transport ts = session.getTransport();

        //3、使用邮箱的用户名和密码连上邮件服务器，发送邮件时，发件人需要提交邮箱的用户名和密码给smtp服务器，用户名和密码都通过验证之后才能够正常发送邮件给收件人。
        ts.connect(mailHost, mailHostUser, mailHostPassword);

        //4、创建邮件
        String mailSubject = generateMailSubject(errorType, message, companyName);
        String mailContent = generateMailContent(errorType, message, companyName);
        Address[] recipients = generateRecipients(notifyEmailList);
        MimeMessage mimeMessage = createSimpleMail(session, mailSubject, mailContent, recipients);

        //5、发送邮件
        ts.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        ts.close();
    }

    public static void main(String[] args) throws Exception {
        Message message = new Message("destination1", "{\"a\":\"18958012838\",\"b\":124,\"c\":{\"d\":543}}");
        message.setId("test_id");
        sendNotifyEmail("系统异常", message, "jjj", Lists.newArrayList("591593903@qq.com"));
    }
}
